package com.example.linphone_flutter;

import org.linphone.core.ChatMessage;
import org.linphone.core.ChatMessageListenerStub;

import java.util.HashMap;
import java.util.Map;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;

public class ChatMessageListener extends ChatMessageListenerStub implements EventChannel.StreamHandler {
    private EventChannel eventChannel;
    private EventChannel.EventSink eventSink;

    ChatMessageListener(BinaryMessenger messenger) {
        eventChannel = new EventChannel(messenger, "linphone_flutter/message");
        eventChannel.setStreamHandler(this);
    }

    @Override
    public void onMsgStateChanged(ChatMessage message, ChatMessage.State state) {
        if (eventSink != null) {
            String localTime = message.getUserData().toString();
            if (state == ChatMessage.State.InProgress) {
                msgStateChange("InProgress",localTime);
            } else if (state == ChatMessage.State.Delivered) {
                msgStateChange("Delivered", localTime);
            } else if (state == ChatMessage.State.DeliveredToUser) {
                msgStateChange("DeliveredToUser", localTime);
            } else if (state == ChatMessage.State.Displayed) {
                msgStateChange("Displayed", localTime);
            } else if (state == ChatMessage.State.NotDelivered) {
                msgStateChange("NotDelivered", localTime);
            } else if (state == ChatMessage.State.FileTransferDone) {
                msgStateChange("FileTransferDone", localTime);
            }
        }
    }

    public void msgStateChange(String stateString, String localTime){
        Map<String, Object> res = new HashMap();
        res.put("type", "messageState");
        res.put("result", stateString);
        res.put("localTime", localTime);
        eventSink.success(res);
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        this.eventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
        this.eventSink = null;
    }
}
